package com.spera.duanxin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.spring.api.web.dao.SmsSendHistoryMapper;
import com.spring.api.web.model.SmsReplyHistory;
import com.spring.api.web.model.SmsSendHistory;
import com.spring.api.web.service.SmsReplyHistoryService;
import com.spring.nbrbt.tools.dateutil.UDate;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.iputil.HttpCUtils;
import com.spring.security.web.iputil.HttpClientUtils;
import com.spring.security.web.model.BaseResult;

public class SxUtil {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private SmsReplyHistoryService smsReplyHistoryService;
	@Resource
	private SmsSendHistoryMapper smsSendHistoryMapper;
	
	
//	private static SmsReplyHistoryService smsReplyHistoryService = SpringContextHolder.getBean(SmsReplyHistoryService.class);
	
	public static String dc_url = JedisCont.getProParm("hy_dc.url");
	public static String dc_username = JedisCont.getProParm("hy_dc.username");
	public static String dc_password = JedisCont.getProParm("hy_dc.password");
	
	public static String qf_url = JedisCont.getProParm("hy_qf.url");
	public static String qf_username = JedisCont.getProParm("hy_qf.username");
	public static String qf_password = JedisCont.getProParm("hy_qf.password");
	
	
	public void checkSms(){
		queryDcInfo();
		queryQfInfo();
	}
	
	public void checkSendSms(){
		logger.debug("发送短信检测: {}", new SimpleDateFormat("hh:mm:ss")
		    	.format(new Date()));
		SmsSendHistory selparm = new SmsSendHistory();
		selparm.setEstimatedsendtime(new Date());
		selparm.setSmsstatus(0);
		List<SmsSendHistory> retList = smsSendHistoryMapper.selectByParm(selparm);
		for(SmsSendHistory one:retList){
			System.out.println("---------->"+one.getId());
			sendSms(one);
		}
	}
	
	public void sendSms(SmsSendHistory one){
		String ret = "";
		Map<String,Object> parm = new HashMap<String,Object>();
		parm.put("account", qf_username);
		parm.put("password", qf_password);
		parm.put("mobile", one.getMobile());
		parm.put("content", one.getContent()+"回T退订【"+one.getSignature()+"】");
		System.out.println("mobile----------->"+one.getMobile());
		try {
//			ret = HttpCUtils.postParameters("http://api.yx.ihuyi.com/webservice/sms.php?method=Submit", parm);
			ret = HttpClientUtils.httpPost("http://api.yx.ihuyi.com/webservice/sms.php?method=Submit", parm);
			Document doc = DocumentHelper.parseText(ret); 
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");

			//保存日志
//			saveSmsLog(one.getMobile(),one.getContent(),smsid,2,code,msg);
//			if("2".equals(code)){
//				
//			}
			SmsSendHistory oneUp = new SmsSendHistory();
			oneUp.setId(one.getId()).setSmsstatus(1).setSendtime(new Date()).setMsg(msg).setSmsid(smsid)
			.setSmssendresult(Integer.parseInt(code));
			smsSendHistoryMapper.updateByPrimaryKeySelective(oneUp);
		} catch (Exception e) {
			e.printStackTrace();
//			saveSmsLog(one.getMobile(),one.getContent(),"",2,"9999","短信接口调用异常："+e.getMessage());
		}
	}
	
	//点触信息回复
	public void queryDcInfo(){
		String ret = "";
		try {
			ret = HttpCUtils.get(dc_url+"?method=GetReply&account="+dc_username+"&password="+dc_password);
			Document doc = DocumentHelper.parseText(ret); 
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");
//			String smsid = root.elementText("smsid");

//			System.out.println(code);
//			System.out.println(msg);
//			System.out.println(smsid);

			if("2".equals(code)){
				System.out.println("回复短信获取成功");
				if(StringUtils.isNotBlank(msg)){
					saveSmsLog(msg,1);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//群发信息回复
	public void queryQfInfo(){
		String ret = "";
		try {
			ret = HttpCUtils.get(qf_url+"?method=GetReply&account="+qf_username+"&password="+qf_password);
			Document doc = DocumentHelper.parseText(ret); 
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");

//			System.out.println(code);
//			System.out.println(msg);

			if("2".equals(code)){
				System.out.println("回复短信获取成功");
				if(StringUtils.isNotBlank(msg)){
					saveSmsLog(msg,2);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//保存短信上行日志
	public void saveSmsLog(String msg,int type){
		List<SmsReplyHistory> smsList = new ArrayList<SmsReplyHistory>();
		if(ApplicationUtils.isNotNull(msg)){
			String[] msgArr = msg.split("\\|\\@\\|");
			for(String msgOne:msgArr){
//				System.out.println("msgOne--->"+msgOne);
				String[] smsOne = msgOne.split(",");
//				for(String s:smsOne){
//					System.out.println("s--->"+s);
//				}
				SmsReplyHistory sms = new SmsReplyHistory(ApplicationUtils.randomUUID(),smsOne[0],smsOne[3],type,smsOne[1],
						UDate.stringToDate(smsOne[2], "yyyy-MM-dd HH:mm:ss"));
				sms.initInfo();
				smsList.add(sms);
			}
		}
		BaseResult sucCount = smsReplyHistoryService.insertByList(smsList);
		System.out.println(sucCount.getMsg());
	}
	
	//保存短信下行日志
	public void saveSmsLog(String phones,String content,String smsid,int type,String smssendresult,String msg){
		List<SmsSendHistory> smsList = new ArrayList<SmsSendHistory>();
		if(ApplicationUtils.isNotNull(content)&&ApplicationUtils.isNotNull(phones)){
			String[] phoneArr = phones.split(",");
			for(String phone:phoneArr){
				SmsSendHistory sms = new SmsSendHistory();
				sms.initInfo();
				sms.setId(ApplicationUtils.randomUUID()).setContent(content).setSendtime(new Date())
				.setSmstype(type).setSmssendresult(Integer.parseInt(smssendresult)).setMobile(phone)
				.setSmsstatus(smssendresult.equals("2")?1:2).setSmsid(smsid).setMsg(msg);
				smsList.add(sms);
			}
		}
		smsSendHistoryMapper.insertByList(smsList);
	}
	
//	public static void main(String[] args) {
//		checkSendSms();
//	}

}
